package com.yilu.driver.ui.activity;

import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.is.common.utils.SPUtils;
import com.is.ui.filter.util.ScreenUtils;
import com.is.ui.selectrecyclerview.DragSelectRecyclerView;
import com.is.ui.selectrecyclerview.DragSelectRecyclerViewAdapter;
import com.is.ui.widget.CustomPopWindow;
import com.is.ui.xrecyclerview.universaladapter.ViewHolderHelper;
import com.is.ui.xrecyclerview.universaladapter.recyclerview.CommonRecycleViewAdapter;
import com.is.ui.xrecyclerview.universaladapter.recyclerview.OnItemClickListener;
import com.yilu.driver.R;
import com.yilu.driver.base.BaseActivity;
import com.yilu.driver.entity.BatchAllResponse;
import com.yilu.driver.entity.StudentApplyResponse;
import com.yilu.driver.mvp.contract.ApplyExamContract;
import com.yilu.driver.mvp.model.ApplyExamModel;
import com.yilu.driver.mvp.presenter.ApplyExamPresenter;
import com.yilu.driver.ui.adapter.ApplyExamSelectAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 报考登记
 *
 * @author Administrator
 * @date 2017/4/15 0015
 */

public class ApplyExamRegistionActivity extends BaseActivity
        implements ApplyExamContract.View, ApplyExamSelectAdapter.ClickListener
        , DragSelectRecyclerViewAdapter.SelectionListener, PopupWindow.OnDismissListener {

    @Bind(R.id.ib_back)
    ImageButton ibBack;
    @Bind(R.id.ib_exit)
    ImageButton ibExit;
    @Bind(R.id.ib_search)
    ImageButton ibSearch;
    @Bind(R.id.mFilterContentView)
    DragSelectRecyclerView mFilterContentView;
    @Bind(R.id.btn_title)
    AppCompatButton btnTitle;
    @Bind(R.id.txt_select)
    TextView txtSelect;
    @Bind(R.id.ll_select)
    LinearLayout llSelect;
    @Bind(R.id.btn_register)
    Button btnRegister;
    private ApplyExamModel model;
    private ApplyExamPresenter presenter;
    private CustomPopWindow mCustomPopWindow;
    private CustomPopWindow mListPopWindow;
    private CommonRecycleViewAdapter<String> batchAdapter;
    private ApplyExamSelectAdapter mAdapter;
    private Integer oprater;//操作人
    private String batch;//批次
    private Integer subject = 1;//科目 默认科目一

    private boolean registion = false;//成绩是否登记
    private List<StudentApplyResponse.DataBean> traineeList;
    private boolean isShowMenu = false;//判断是否弹出菜单 默认否

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_apply_exam;
    }

    @Override
    protected void initViewsAndEvents() {
        oprater = (Integer) SPUtils.get(mContext, "id", 0);
        traineeList = new ArrayList<>();
        mFilterContentView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public void initPresenter() {
        presenter = new ApplyExamPresenter(mContext);
        model = new ApplyExamModel();
        presenter.setVM(this, model);
    }

    private void getBatchAll(Integer subject, Integer operator) {
        JSONObject json = new JSONObject();
        try {
            json.put("subject", subject);
            json.put("operator", operator);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.getBatchAll(json);
    }

    @Override
    public void returnApplyStudent(StudentApplyResponse studentApplyResponse) {
        traineeList = studentApplyResponse.getData();
        mAdapter = new ApplyExamSelectAdapter(studentApplyResponse.getData(), this);
        mFilterContentView.setAdapter(mAdapter);
        mAdapter.setSelectionListener(this);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void returnExamRoster(StudentApplyResponse rosterResponse) {
        traineeList = rosterResponse.getData();
        //    adapter.replaceAll(rosterResponse.getData());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void returnBatchAll(BatchAllResponse batchAllResponse) {
        batchAdapter.replaceAll(batchAllResponse.getData());
        batchAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * 显示顶部选项菜单
     * 已登记、未登记
     */
    private void showPopMenu() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu_registion, null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .size(ScreenUtils.getScreenWidth(mContext) / 3, ViewGroup.LayoutParams.WRAP_CONTENT)//显示大小
                .setFocusable(false)
                .setOnDissmissListener(this)
                .create()
                .showAsDropDown(btnTitle, 0, 10);
    }

    /**
     * 选项菜单的控制方法
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.menu1:
                        btnTitle.setText("已登记");
                        registion = true;
                        break;
                    case R.id.menu2:
                        btnTitle.setText("未登记");
                        registion = false;
                        break;
                }
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
            }
        };
        contentView.findViewById(R.id.menu1).setOnClickListener(listener);
        contentView.findViewById(R.id.menu2).setOnClickListener(listener);
    }

    @OnClick({R.id.btn_title, R.id.ll_select, R.id.btn_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title:
                isShowMenu = !isShowMenu;
                if (isShowMenu) {
                    showPopMenu();
                }
                break;
            case R.id.ll_select:
                showPopList();
                break;
            case R.id.btn_register:
                Bundle bundle = new Bundle();
                ArrayList<StudentApplyResponse.DataBean> selectedTrainee = new ArrayList<>();
                for (StudentApplyResponse.DataBean dateBean : traineeList) {
                    if (dateBean.isChecks()) {
                        selectedTrainee.add(dateBean);
                    }
                }
                //   bundle.putParcelableArrayList("list", selectedTrainee);
                bundle.putInt("subject", subject);
                readyGo(ScoreRegisterActivity.class, bundle);
                break;
        }
    }

    /**
     * 弹出筛选列表
     */
    private void showPopList() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_select, null);
        //处理popWindow 显示内容
        handleListView(contentView);
        //创建并显示popWindow
        mListPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .setOutsideTouchable(false)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.getScreenHeighth(mContext) / 2)//显示大小
                .create()
                .showAsDropDown(llSelect, 0, 0);
    }

    /**
     * 选项菜单的控制方法
     * 处理弹出显示内容、点击事件等逻辑
     * 筛选列表
     *
     * @param contentView
     */
    private void handleListView(View contentView) {
        getBatchAll(1, oprater);
        RecyclerView rcBatch = (RecyclerView) contentView.findViewById(R.id.rc_batch);
        batchAdapter = new CommonRecycleViewAdapter<String>(mContext, R.layout.item_batch) {
            @Override
            public void convert(ViewHolderHelper helper, String batch) {
                TextView txtBatch = helper.getView(R.id.txt_batch);
                txtBatch.setText(batch);
            }
        };
        rcBatch.setLayoutManager(new GridLayoutManager(mContext, 3));
        rcBatch.setAdapter(batchAdapter);

        batchAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, View view, Object o, int position) {
                batch = batchAdapter.get(position);
            }

            @Override
            public boolean onItemLongClick(ViewGroup parent, View view, Object o, int position) {
                return false;
            }
        });
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.btn_subject_one:
                        subject = 1;
                        getBatchAll(1, oprater);
                        break;
                    case R.id.btn_subject_two:
                        subject = 2;
                        getBatchAll(2, oprater);
                        break;
                    case R.id.btn_subject_three:
                        subject = 3;
                        getBatchAll(3, oprater);

                        break;
                    case R.id.btn_subject_four:
                        subject = 4;
                        getBatchAll(4, oprater);
                        break;
                    case R.id.btn_confirm:
                        txtSelect.setText(subject + batch);
                        getStudentApply(oprater, "", "", 1, 10);
                        mListPopWindow.dissmiss();
                        break;
                }
            }
        };
        contentView.findViewById(R.id.btn_subject_one).setOnClickListener(listener);
        contentView.findViewById(R.id.btn_subject_two).setOnClickListener(listener);
        contentView.findViewById(R.id.btn_subject_three).setOnClickListener(listener);
        contentView.findViewById(R.id.btn_subject_four).setOnClickListener(listener);
        contentView.findViewById(R.id.btn_confirm).setOnClickListener(listener);
    }

    private void getStudentApply(Integer operator, String name, String idNumber, Integer start, Integer length) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("operator", operator);
            jsonObject.put("name", name);
            jsonObject.put("idNumber", idNumber);
            jsonObject.put("start", start);
            jsonObject.put("length", length);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        presenter.getApplyStudent(jsonObject);
    }

    @Override
    public void onClick(int index) {
        mAdapter.toggleSelected(index);
    }

    @Override
    public void onLongClick(int index) {
        mFilterContentView.setDragSelectActive(true, index);
    }

    @Override
    public void onDragSelectionChanged(int count) {

    }

    @Override
    public void onDismiss() {
        btnTitle.setTextColor(getResources().getColor(R.color.b_c_fafafa));
    }
}
